package com.module.frame.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.CallSuper
import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType

/**
 * 主要处理BaseViewModel 根据泛型创建
 */
abstract class BaseVmFragment<VM : BaseFrameViewModel> : BaseLazyFragment() {

    lateinit var mViewModel: VM

    /**
     * 绑定ViewModel
     */
    abstract fun bingViewModel()

    abstract fun getLayoutView(
        layoutInflater: LayoutInflater,
        parent: ViewGroup?,
        attachToParent: Boolean
    ): View?

    @CallSuper
    override fun initView() {
        //vm初始化
        mViewModel = createViewModel()
        bingViewModel()
    }

    /**
     * 重载，不使用父类的设置试图，而是使用 getLayoutView
     */
    override fun setContentView(layoutInflater: LayoutInflater, parent: ViewGroup?) {
        val layoutView = getLayoutView(layoutInflater, parent, false);
        mRootView = layoutView ?: layoutInflater.inflate(getLayoutId(), null)

    }


    /**
     * 创建viewModel
     */
    private fun createViewModel(): VM {
        return try {
            val mClass =
                (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<VM>
             ViewModelProvider(this).get(mClass)
        } catch (e: Exception) {
            BaseFrameViewModel() as VM
        }
    }

}